package org.ba.ovk.crawler;

import lombok.AllArgsConstructor;
import lombok.val;

import org.apache.commons.collections.CollectionUtils;
import org.ba.ovk.msg.CrawlOvkMsg;
import org.ba.ovk.msg.ParseProgramMsg;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

@AllArgsConstructor
public class CrawlOvkHadler {
	public EventBus bus;
	final WebClient webClient = new WebClient();

	@Subscribe
	public void handleSendEmailCommand(final CrawlOvkMsg command) {
		try {
			final HtmlPage page = webClient.getPage("http://www.cvk.gov.ua/pls/vnd2014/WP033?PT001F01=910&pf7331=" + command.ovkId);
			final HtmlTable table = (HtmlTable) page.getByXPath("//table[@class='t2']").get(1);
			if (table == null || CollectionUtils.isEmpty(table.getRows())) {
				return;
			}
			int nrow = 0;
			for (final HtmlTableRow row : table.getRows()) {

				nrow++;
				if (nrow <= 1) {
					continue;
				}

				if (CollectionUtils.isEmpty(row.getCells())) {
					continue;
				}

				val ahref = ((HtmlAnchor) row.getCell(3).getFirstChild());
				val href = ahref.getAttribute("href");
				val url = page.getFullyQualifiedUrl(href);
				val parseCandidateMsg =
						new ParseProgramMsg(command.ovkId, getSimpleStr(row.getCell(0).asText()), getSimpleStr(row.getCell(2).asText()), url);
				bus.post(parseCandidateMsg);
			}
		}
		catch (Exception e) {
			//log.error(e);
		}
	}

	private static String getSimpleStr(final String original) {
		return original.replaceAll("\n", " ").replaceAll("\t", " ").replaceAll("\r", " ").replaceAll("  ", " ");
	}
}
